//
//  SwiftNetworkTool.swift
//  OCNetworkTool
//
//  Created by Shenzhen_iOS_07 on 16/11/26.
//  Copyright © 2016年 Shenzhen_iOS_07. All rights reserved.
//

import Foundation
import AFNetworking

class NetworkTool: AFHTTPSessionManager {
    /// 单例
    static let shared: NetworkTool = {
        let tool = NetworkTool()
        //添加AFN可以接受的数据的类型
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()

    /// 网络中间层的接口方法
    ///
    /// - Parameters:
    ///   - url: 请求地址
    ///   - parameters: 参数
    ///   - method: 请求方式
    ///   - callBack: 请求完成回调闭包
    func request(url: String, parameters: [String: Any]? = nil, method: String, callBack:@escaping (_ responseObject: Any?)->()) {
        
        //网络请求成功的闭包(请求成功之后要干的事)
        let success = { (task: URLSessionDataTask, response: Any?) in
            callBack(response)
        }
        
        //网络请求失败的闭包
        let failure = { (task: URLSessionDataTask?, error: Error) in
            print(error)
            //如果请求失败,仍然需要执行callBack
            callBack(nil)
        }
        
        //发起get请求
        if method == "GET" {
            self.get(url, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
        //发起post请求
        if method == "POST" {
            self.post(url, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
